package com.joe.socket.Controller;

import com.joe.socket.Server.WebSocketServer;
import com.joe.socket.Model.ChatMessage;
import com.joe.socket.Dao.MessageHistoryDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/chat")
@CrossOrigin(origins = "*")
public class ChatController {

    @Autowired
    private WebSocketServer webSocketServer;

    @Autowired
    private MessageHistoryDao messageHistoryDao;

    /**
     * 获取服务器统计信息
     */
    @GetMapping("/stats")
    public Map<String, Object> getServerStats() {
        return webSocketServer.getServerStats();
    }

    /**
     * 获取历史消息
     */
    @GetMapping("/history")
    public Map<String, Object> getMessageHistory(@RequestParam(defaultValue = "50") int count) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<ChatMessage> messages = webSocketServer.getRecentMessages(count);
            result.put("success", true);
            result.put("messages", messages);
            result.put("count", messages.size());
            result.put("total", messageHistoryDao.getMessageCount());
        } catch (Exception e) {
            result.put("success", false);
            result.put("error", "获取历史消息失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 获取指定用户的消息历史
     */
    @GetMapping("/history/user/{username}")
    public Map<String, Object> getUserMessageHistory(@PathVariable String username) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<ChatMessage> messages = messageHistoryDao.getMessagesByUser(username);
            result.put("success", true);
            result.put("messages", messages);
            result.put("count", messages.size());
            result.put("username", username);
        } catch (Exception e) {
            result.put("success", false);
            result.put("error", "获取用户消息历史失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 获取系统消息
     */
    @GetMapping("/history/system")
    public Map<String, Object> getSystemMessageHistory() {
        Map<String, Object> result = new HashMap<>();
        try {
            List<ChatMessage> messages = messageHistoryDao.getSystemMessages();
            result.put("success", true);
            result.put("messages", messages);
            result.put("count", messages.size());
        } catch (Exception e) {
            result.put("success", false);
            result.put("error", "获取系统消息失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 清空历史记录（管理员功能）
     */
    @DeleteMapping("/history/clear")
    public Map<String, Object> clearHistory() {
        Map<String, Object> result = new HashMap<>();
        try {
            int count = messageHistoryDao.getMessageCount();
            messageHistoryDao.clearHistory();
            result.put("success", true);
            result.put("message", "历史记录已清空");
            result.put("clearedCount", count);
        } catch (Exception e) {
            result.put("success", false);
            result.put("error", "清空历史记录失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 获取历史统计信息
     */
    @GetMapping("/history/stats")
    public Map<String, Object> getHistoryStats() {
        Map<String, Object> result = new HashMap<>();
        try {
            int totalMessages = messageHistoryDao.getMessageCount();
            List<ChatMessage> systemMessages = messageHistoryDao.getSystemMessages();

            result.put("success", true);
            result.put("totalMessages", totalMessages);
            result.put("systemMessages", systemMessages.size());
            result.put("userMessages", totalMessages - systemMessages.size());

            // 获取最活跃的用户（简单统计）
            Map<String, Long> userMessageCount = messageHistoryDao.getAllMessages().stream()
                    .filter(msg -> msg.getType() == ChatMessage.MessageType.TEXT)
                    .collect(java.util.stream.Collectors.groupingBy(ChatMessage::getSender, java.util.stream.Collectors.counting()));

            result.put("userStats", userMessageCount);

        } catch (Exception e) {
            result.put("success", false);
            result.put("error", "获取历史统计失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 获取当前在线用户列表
     */
    @GetMapping("/users/online")
    public Map<String, Object> getOnlineUsers() {
        Map<String, Object> result = new HashMap<>();
        try {
            List<String> onlineUsers = webSocketServer.getOnlineUsers();
            result.put("success", true);
            result.put("users", onlineUsers);
            result.put("count", onlineUsers.size());
            result.put("timestamp", System.currentTimeMillis());
        } catch (Exception e) {
            result.put("success", false);
            result.put("error", "获取在线用户失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 健康检查接口
     */
    @GetMapping("/health")
    public Map<String, Object> healthCheck() {
        Map<String, Object> health = new HashMap<>();
        health.put("status", "UP");
        health.put("timestamp", LocalDateTime.now().toString());
        health.put("service", "Socket Chat Server");
        health.put("version", "1.0.0");

        // 添加服务器统计信息
        try {
            Map<String, Object> stats = webSocketServer.getServerStats();
            health.put("serverStats", stats);
        } catch (Exception e) {
            health.put("serverStatsError", e.getMessage());
        }

        return health;
    }

    /**
     * 系统广播消息（管理员功能）
     */
    @PostMapping("/broadcast")
    public Map<String, Object> broadcastSystemMessage(@RequestBody Map<String, String> request) {
        Map<String, Object> response = new HashMap<>();

        String message = request.get("message");
        if (message != null && !message.trim().isEmpty()) {
            response.put("success", true);
            response.put("message", "广播消息已发送");
            response.put("content", message);
            response.put("timestamp", LocalDateTime.now().toString());

            // 这里可以调用WebSocketServer的广播方法
            // 暂时返回成功，实际功能需要WebSocketServer支持
        } else {
            response.put("success", false);
            response.put("error", "消息内容不能为空");
        }

        return response;
    }

    /**
     * 获取服务器信息
     */
    @GetMapping("/info")
    public Map<String, Object> getServerInfo() {
        Map<String, Object> info = new HashMap<>();
        info.put("name", "Socket通信服务器");
        info.put("version", "1.0.0");
        info.put("description", "基于Spring Boot + WebSocket的实时聊天系统");
        info.put("technology", "Spring Boot, WebSocket, REST API");
        info.put("author", "Joe");
        info.put("timestamp", LocalDateTime.now().toString());
        return info;
    }

    /**
     * 获取服务器状态详情
     */
    @GetMapping("/status")
    public Map<String, Object> getServerStatus() {
        Map<String, Object> status = new HashMap<>();

        try {
            // 基本服务器信息
            status.put("serverTime", LocalDateTime.now().toString());
            status.put("javaVersion", System.getProperty("java.version"));
            status.put("os", System.getProperty("os.name"));

            // 应用状态
            Map<String, Object> stats = webSocketServer.getServerStats();
            status.put("serverStats", stats);

            // 内存信息
            Runtime runtime = Runtime.getRuntime();
            status.put("memory", new HashMap<String, Object>() {{
                put("totalMemory", runtime.totalMemory());
                put("freeMemory", runtime.freeMemory());
                put("maxMemory", runtime.maxMemory());
                put("usedMemory", runtime.totalMemory() - runtime.freeMemory());
            }});

            status.put("success", true);

        } catch (Exception e) {
            status.put("success", false);
            status.put("error", "获取服务器状态失败: " + e.getMessage());
        }

        return status;
    }

    /**
     * 测试接口
     */
    @GetMapping("/test")
    public Map<String, Object> testEndpoint() {
        Map<String, Object> result = new HashMap<>();
        result.put("message", "Socket聊天服务器API运行正常");
        result.put("timestamp", System.currentTimeMillis());
        result.put("endpoints", java.util.Arrays.asList(
                "/api/chat/health - 健康检查",
                "/api/chat/stats - 服务器统计",
                "/api/chat/history - 历史消息",
                "/api/chat/users/online - 在线用户",
                "/api/chat/info - 服务器信息"
        ));
        return result;
    }
}